package com.esp.studentManagementSystem.service.impl;

import com.esp.studentManagementSystem.entity.QSysMenu;
import com.esp.studentManagementSystem.entity.QSysRoleMenu;
import com.esp.studentManagementSystem.entity.QSysRoleUser;
import com.esp.studentManagementSystem.pojo.vo.SecurityGrantedAuthorityVO;
import com.esp.studentManagementSystem.service.MenuBOService;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuBOServiceImpl implements MenuBOService {

    @Autowired
    private JPAQueryFactory jpaQuery;

    @Override
    public List<SecurityGrantedAuthorityVO> getCodesByUserId(Integer userId) {
        QSysMenu qSysMenu = QSysMenu.sysMenu;
        QSysRoleMenu qSysRoleMenu = QSysRoleMenu.sysRoleMenu;
        QSysRoleUser qSysRoleUser = QSysRoleUser.sysRoleUser;
        List<String> codes = jpaQuery.select(qSysMenu.code)
                .from(qSysMenu)
                .where(qSysMenu.id.in(
                        JPAExpressions.select(qSysRoleMenu.id.mid)
                                .from(qSysRoleMenu)
                                .where(qSysRoleMenu.id.rid.in(
                                        JPAExpressions.select(qSysRoleUser.id.rid)
                                                .from(qSysRoleUser)
                                                .where(qSysRoleUser.id.uid.eq(userId))
                                ))
                ))
                .fetch();;
        return codes.stream().map(SecurityGrantedAuthorityVO::new).toList();
    }
}

